package com.ibm.risk.irmp.base.file.service.impl;

import com.ibm.risk.irmp.base.file.service.FileStoreService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Value;

import java.io.File;
import java.nio.file.FileSystemException;
import java.nio.file.Files;
import java.util.Date;

@Slf4j
public class LocalFileStoreServiceImpl implements FileStoreService {
	private String storagePath;

	@Value("${app.irmp.base.filestore.local.path:/tmp/}")
	public void setStoragePath(String path) {
		if (!path.endsWith("/")) {
			path = path + "/";
		}
		this.storagePath = path;
	}

	@Override
	public String upload(File localFile, String path, String fileName) throws Exception {
		if (path.startsWith("/")) {
			path = path.substring(1);
		}
		String dts = DateFormatUtils.format(new Date(), "yyyyMMddHHmmssSSS");
		String storageFilePath = storagePath + path;
		if (!path.endsWith("/")) {
			storageFilePath += "/";
		}
		storageFilePath += dts.substring(0, 8);
		if (!new File(storageFilePath).exists()) {
			new File(storageFilePath).mkdirs();
		}
		String fileUrl = storageFilePath
						+ "/" + dts.substring(8)
						+ RandomStringUtils.randomAlphanumeric(3) + fileName;
		localFile.renameTo(new File(fileUrl));
		log.info("File {} has been saved to {}", localFile, fileUrl);
		return fileUrl;
	}



	@Override
	public void download(String fileUrl, File localFile) throws Exception {

		File file = new File(fileUrl);
		try {
			Files.createSymbolicLink(file.toPath(), localFile.toPath());
		} catch (FileSystemException | UnsupportedOperationException e) {
			log.warn("Unable to create symbolic link {}, fallback to copy!, root cause: {}", localFile, e.getMessage());
			Files.copy(file.toPath(), localFile.toPath());
		}
	}

	@Override
	public void delete(String remoteUri) throws Exception {
		new File(storagePath + remoteUri).delete();
	}

	@Override
	public String getFileStoreSys() {
		return "local";
	}
}
